package com.ciwong.epaper.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.WindowManager;

import com.ciwong.epaper.application.EApplication;
import com.ciwong.libs.utils.CWLog;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * 登录公共工具类
 * Created by lqi on 2017/2/22.
 */
public class DeviceUtil {
    public static int getDeviceWidth(Context context) {
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        return manager.getDefaultDisplay().getWidth();
    }

    public static String getApplicationId(Context context) {
        int versionCode = 0;
        PackageManager packageManager = context.getPackageManager();
        String packageName = context.getPackageName();
        int flags = 0;
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(packageName, flags);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageInfo != null) {
            versionCode = packageInfo.versionCode;
        }
        return String.valueOf(versionCode);
    }

    public static String getVersionName(Context context) {
        String VersionName = null;
        PackageManager packageManager = context.getPackageManager();
        String packageName = context.getPackageName();
        int flags = 0;
        PackageInfo packageInfo = null;
        try {
            packageInfo = packageManager.getPackageInfo(packageName, flags);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (packageInfo != null) {
            VersionName = packageInfo.versionName;
        }
        return VersionName;
    }


    public static String getPhoneVersion() {
        String phoneVersion = Build.MODEL;
        try {
            return URLEncoder.encode(phoneVersion, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }


    }

    public static String getOsVersion() {
        String osVersion = Build.VERSION.RELEASE;
        try {
            return URLEncoder.encode(osVersion, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getPublicKey(String clientSecrect) {
        String publicKey = clientSecrect.substring(0, 15);
        return publicKey;
    }

    public static String getSign(HashMap<String, String> params) {
        StringBuffer paramsUrl = null;
        StringBuffer clientParam = null;
        StringBuffer rfTokenParam = null;
        StringBuffer publickeyParam = null;
        if (params != null) {
            Iterator<String> it = params.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                String value = params.get(key);
                if (clientParam == null) {
                    clientParam = new StringBuffer();
                }
                if (rfTokenParam == null) {
                    rfTokenParam = new StringBuffer();
                }
                if (publickeyParam == null) {
                    publickeyParam = new StringBuffer();
                }
                if (key.equals("clientId")) {
                    clientParam = clientParam.append(key).append("=").append(value);
                } else if (key.equals("refreshToken")) {
                    rfTokenParam = rfTokenParam.append(key).append("=").append(value);
                } else if (key.equals("publicKey")) {
                    publickeyParam = publickeyParam.append(key).append("=").append(value);
                }
            }
            paramsUrl = new StringBuffer();
            paramsUrl = paramsUrl.append(clientParam).append("&").append(publickeyParam).append("&").append(rfTokenParam);
        }
        if (!TextUtils.isEmpty(paramsUrl)) {
            Log.i("lqi", "paramsUrl: " + paramsUrl + "SECRECT: " + EConstants.CLIENT_SECRECT);
            return hmacSha1(paramsUrl.toString(), EConstants.CLIENT_SECRECT);
        } else {
            return null;
        }
    }

    /**
     * 获取 hmacSha1
     *
     * @param data
     * @param key
     * @return
     */
    public static String hmacSha1(String data, String key) {
        if (TextUtils.isEmpty(data) || TextUtils.isEmpty(key)) {
            return "";
        }
        String type = "HmacSHA1";
        StringBuilder sb = new StringBuilder();
        try {
            Mac mac = Mac.getInstance(type);
            SecretKeySpec secret = new SecretKeySpec(key.getBytes("UTF-8"), mac.getAlgorithm());
            mac.init(secret);
            byte[] digest = mac.doFinal(data.getBytes());
            for (byte b : digest) {
                sb.append(byteToHexString(b));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();

    }

    private static String byteToHexString(byte ib) {
        char[] Digit = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
        };
        char[] ob = new char[2];
        ob[0] = Digit[(ib >>> 4) & 0X0f];
        ob[1] = Digit[ib & 0X0F];
        String s = new String(ob);
        return s;
    }

    public static boolean isPad() {
        EApplication eApplication = EApplication.getInstance();
        String packageName = "";
        if (eApplication != null) {
            packageName = eApplication.getPackageName();
        }
        if ("com.ciwong.newspaperhd".equals(packageName)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断当前手机是否有ROOT权限
     *
     * @return
     */
    public static boolean isRoot() {
        boolean bool = false;
        try {
            if ((!new File("/system/bin/su").exists()) && (!new File("/system/xbin/su").exists())) {
                bool = false;
            } else {
                bool = true;
            }
            CWLog.d("DeviceUtil", "bool = " + bool);
        } catch (Exception e) {
        }
        return bool;
    }
}
